import React, { useEffect, useState } from 'react';
import { connect } from 'umi';
import { history } from 'umi';
import { eventTrack } from '@/utils/track';
import { Form, Button, Card, Radio, message, Upload, Icon, Table, Divider, Modal, Progress } from 'antd';
import cookie from 'js-cookie';
import clone from 'lodash/clone';
import xss from 'xss';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { getOrganization, download } from '@/utils/utils';
import styles from './VacationBalance.less';

const ImportVacation = ({ form, dispatch, loading, vacationBalance, user, ...rags }) => {
    const { demoTable } = vacationBalance;
    // const User = user.currentUser; // 登陆人信息

    const id = rags.location.query.id || ''; // 列表传输过来的公司id

    const [radioValue, setRadioValue] = useState(0);
    const [columns, setColumns] = useState(null);

    const [uploading, setUploading] = useState(false);
    const [fileInfo, setFileInfo] = useState(null);
    const [returnFileInfo, setReturnFileInfo] = useState(null);
    const [modalType, setModalType] = useState(null);
    const commonColumns = [
        {
            title: '工号',
            dataIndex: 'userNo',
            key: 'userNo',
            render: () => <div className={styles.block}></div>
        },
        {
            title: '姓名',
            dataIndex: 'employeeName',
            key: 'employeeName',
            render: () => <div className={styles.block}></div>
        }
    ];
    const getColumns = () => {
        let newArr = [];
        if (getOrganization(id).area === 'cn') {
            const arr = [
                {
                    title: '年假(发放天数）',
                    dataIndex: 'CommonYear',
                    key: 'CommonYear'
                }
            ];
            newArr = clone(commonColumns).concat(arr);
        } else {
            const arr = [
                {
                    title: '年假(发放天数）',
                    dataIndex: 'CommonYear',
                    key: 'CommonYear'
                },
                {
                    title: '病假(发放天数）',
                    dataIndex: 'CommonSick',
                    key: 'CommonSick'
                },
                {
                    title: '住院假(发放天数）',
                    dataIndex: 'SgHospital',
                    key: 'SgHospital'
                }
            ];
            newArr = clone(commonColumns).concat(arr);
        }
        setColumns(newArr);
    };

    const radioChange = e => {
        setRadioValue(e.target.value);
    };
    const downTemplate = async () => {
        download({
            getData: () =>
                dispatch({
                    type: 'vacationBalance/downTemplate',
                    payload: {
                        companyId: id
                    }
                })
        });
    };
    const renderModalType = () => {
        if (!modalType) {
            return (
                <Progress
                    type="circle"
                    percent={100}
                    width={80}
                    format={() => <span style={{ color: '#FE9E01' }}>上传中...</span>}
                    strokeColor="#FE9E01"
                />
            );
        }
        if (modalType === 'success') {
            return <Progress type="circle" percent={100} width={80} />;
        }
        if (modalType === 'error') {
            return <Progress type="circle" percent={100} width={80} status="exception" />;
        }
        return '';
    };

    // 自定义上传
    const customRequest = async ({ file }) => {
        if (file.name.toLowerCase().indexOf('xlsx') > -1 || file.name.toLowerCase().indexOf('xls') > -1) {
            setUploading(true);
            const formData = new FormData();
            formData.append('file', file);
            formData.append('expires', radioValue);
            formData.append('companyCode', id);

            setFileInfo(file);
            fetch('/api/oa/v1/stream/vocation/importdata', {
                method: 'POST',
                headers: {
                    Authorization: cookie.get('Authorization')
                },
                body: formData
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 10000) {
                        setModalType('success');
                        setTimeout(() => {
                            setUploading(false);
                            setModalType(null);
                            history.push({
                                pathname: '/office/personnelManagement/attendance/vacationBalance'
                            });
                        }, 3000);
                    } else if (data.code === 10301) {
                        setReturnFileInfo(data.msg);
                        setModalType('error');
                        setTimeout(() => {
                            setUploading(false);
                            setModalType(null);
                        }, 3000);
                    } else {
                        message.error(data.msg);
                        setUploading(false);
                    }
                });
        } else {
            message.error('您上传的文件格式不正确,请重新上传！');
        }
    };

    const delectUploadingInfo = () => {
        setReturnFileInfo(null);
    };
    useEffect(() => {
        getColumns();
    }, []);
    return (
        <PageHeaderWrapper>
            <Card bordered={false} title="批量发放余额">
                <ul className={styles.step}>
                    <li>
                        <i className={styles.num}>1</i>
                        <div>
                            下载员工假期余额模板：
                            <Button
                                type="primary"
                                ghost
                                onClick={() => {
                                    downTemplate();
                                    // 埋点
                                    eventTrack({
                                        eventName: 'personnel_management_attendance_vacationBalance_import_click',
                                        eventProps: {
                                            label: '假期统计-批量发放余额'
                                        }
                                    });
                                }}
                                loading={loading.effects['vacationBalance/downTemplate']}
                            >
                                <Icon type="download" />
                                下载模板
                            </Button>
                        </div>
                    </li>
                    <li>
                        <i className={styles.num}>2</i>
                        <div>
                            下载模板后，填写假期余额Excel表（表格示例图如下）：
                            <Table
                                dataSource={demoTable}
                                columns={columns}
                                pagination={false}
                                style={{ marginTop: 15 }}
                            />
                        </div>
                    </li>
                    <li>
                        <i className={styles.num}>3</i>
                        <div>请上传修改后的员工假期余额Excel的文件，选择需发放余额的有效时间：</div>
                    </li>
                </ul>
                <div style={{ margin: '15px 0 40px 55px' }}>
                    <div style={{ marginBottom: 15 }}>
                        <Radio.Group defaultValue={radioValue} onChange={radioChange}>
                            <Radio value={0}>发放今年余额</Radio>
                            <Radio value={1}>发放明年余额</Radio>
                        </Radio.Group>
                    </div>
                    <Upload
                        customRequest={customRequest}
                        showUploadList={false}
                        accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                    >
                        <Button
                            type="primary"
                            ghost
                            onClick={() => {
                                // 埋点
                                eventTrack({
                                    eventName: 'personnel_management_attendance_vacationBalance_import_upload_click',
                                    eventProps: {
                                        label: '批量发放余额-上传文件'
                                    }
                                });
                            }}
                        >
                            <Icon type="upload" />
                            上传文件
                        </Button>
                    </Upload>

                    {returnFileInfo ? (
                        <div className={styles.uploadingInfo}>
                            <Icon
                                type="close"
                                className={styles.colse}
                                onClick={() => {
                                    delectUploadingInfo();
                                }}
                            />
                            <Icon type="close-circle" className={styles.circle} />
                            <text
                                // eslint-disable-next-line react/no-danger
                                dangerouslySetInnerHTML={{
                                    __html: xss(returnFileInfo)
                                }}
                            />
                        </div>
                    ) : (
                        ''
                    )}
                </div>
                <Divider />
                <ul style={{ color: 'rgba(0,0,0,0.45)' }}>
                    <li>温馨提示</li>
                    <li>
                        1、上传成功后，首次上传“员工假期余额”表，Excel中的员工假期余额会批量增加系统中的假期余额，再次上传“员工假期余额”表，Excel中的员工假期余额会覆盖系统中的假期余额。
                    </li>
                    <li>
                        2、上传的Excel表，只支持对员工假期余额批量增加，如需减少余额可在“修改假期余额”里单独对员工减少假期余额，输入的数值支持：小数（保留一位小数）、空值（不影响系统假期余额），不支持负数。
                    </li>
                    <li>
                        3、Excel表的命名和列表的文字不允许更改！列表表头都不可改变顺序或删除重新添加，否则会上传不成功。
                    </li>
                    <li>4、Excel表不支持批量发放调休余额，可在加班记录表里的“手动补录”补录加班时长。</li>
                </ul>
            </Card>
            <Modal
                title={null}
                visible={uploading}
                footer={null}
                maskClosable={false}
                keyboard={false}
                closable={false}
                width={300}
                height={182}
                centered
            >
                <div
                    style={{
                        textAlign: 'center'
                    }}
                >
                    {renderModalType()}
                    <div
                        style={{
                            marginTop: 15,
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap'
                        }}
                    >
                        <Icon type="paper-clip" style={{ marginRight: 5 }} />
                        {fileInfo && fileInfo.name}
                    </div>
                </div>
            </Modal>
        </PageHeaderWrapper>
    );
};

export default connect(({ loading, vacationBalance, user }) => ({
    user,
    vacationBalance,
    loading
}))(Form.create()(ImportVacation));
